/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import PropTypes from "prop-types";
import { Button, message } from "antd";
import { debounce } from "lodash";
import request from "@/utils/request";

export default class DownLoad extends Component {
  state = {
    loading: false,
  };

  downLoad = debounce(
    () => {
      const { url, dl, params, page, type } = this.props;
      this.setState({ loading: true });
      let payload = {
        ...params,
        page,
        dl,
      };
      if (dl == "2" && type == "all") {
        delete payload.cmId;
        delete payload.page;
      }

      request(url, {
        method: "POST",
        body: payload,
      })
        .then(res => {
          let href;
          if (res.code == 0) {
            if (res.data.path && typeof res.data.path == "string") {
              href = res.data.path;

              let downloadElement = document.createElement("a");
              downloadElement.href = href;
              document.body.appendChild(downloadElement);
              downloadElement.click();
              document.body.removeChild(downloadElement);
            }
          } else {
            message.error(res.msg);
          }

          this.setState({ loading: false });
        })
        .catch(err => {
          this.setState({ loading: false });
        });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  render() {
    const { loading } = this.state;
    const { title } = this.props;
    return (
      <span>
        <Button type="primary" icon="download" onClick={this.downLoad} loading={loading}>
          {title}
        </Button>
      </span>
    );
  }
}

DownLoad.propTypes = {
  url: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
};
